package com.jk.demo.thread;

/**
 * 守护线程接收到 InterruptedException 信号会停止生命周期
 */
public class DaemonThreadInterrupt {
    public static Thread thread;

    public void execut(Runnable task) {
        thread = new Thread(()->{
            Thread thread2 = new Thread(task,"任务线程");
            thread2.setDaemon(true);
            thread2.start();
            try {
                thread2.join();//入队阻塞,执行线程 通过interrupt 设置 interrupt 状态
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                System.out.println("1111");
                e.printStackTrace();
            }
        },"执行线程");
        thread.start();

    }

    public void stop() {
        // interrupt0();  // set interrupt status

        thread.interrupt();
    }

    public static void main(String[] args) {
        DaemonThreadInterrupt daemonThreadInterrupt = new DaemonThreadInterrupt();
        daemonThreadInterrupt.execut(()->{
            while(true) {
                System.out.println("程序运行");
                try {
                    thread.sleep(1_000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println("2222");
                    e.printStackTrace();
                }
            }
        });
        daemonThreadInterrupt.stop();
    }
}

